﻿<?php
error_reporting(0);
$root_path = 'http://ielearn.rmutl.ac.th';
$file_name = 'service.php';

ini_set('default_charset', 'utf-8');

include("function.php");
condb();
if(isset($_GET['method'])){
	$method = $_GET['method'];
}else if(isset($_POST['method'])){
	$method = $_POST['method'];
}

call_user_func("$method",$input);

#format=json&method=login&m_username=admin&m_password=admin
function login()
{
	if(isset($_GET['m_username'])){
		$m_username = $_GET['m_username'];
	}else if(isset($_POST["m_username"])){
		$m_username = $_POST["m_username"];
	}
	
	if(isset($_GET['m_password'])){
		$m_password = $_GET['m_password'];
	}else if(isset($_POST["m_password"])){
		$m_password = $_POST["m_password"];
	}
	
	$sql = "select * from member where m_username='$m_username' and m_password='$m_password' and status_id=1";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$numrow = mysql_num_rows($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		
		if($numrow > 0){
			$arrCol["result"] = "OK";
		}else{
			$arrCol["result"] = "ERROR";
		}
		array_push($resultArray,$arrCol);
	}
	mysql_close($objConnect);

	echo json_encode($resultArray);
	/*if(mysql_num_rows($res) == 1)
	{
		$row = mysql_fetch_assoc($res);
		$data['result'] = 'OK';
		$data['member'] = $row;
	}
	else
	{
		$data['result'] = 'ERROR';
	}*/
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	//phpinfo();
	//createOutput($format, $data);
}

#format=json&method=forgetpass&m_username=teacher&m_email=teacher@gmail.com
function forgetpass()
{
	global $cfg_domain;
	if(isset($_GET['m_username'])){
		$m_username=$_GET['m_username'];
	}else if($_POST['m_username']){
		$m_username=$_POST['m_username'];
	} 
	if($_GET['m_email']){
		$m_email=$_GET['m_email'];
	}else if($_POST['m_email']){
		$m_email=$_POST['m_email'];
	}
	

	$row=mysql_fetch_assoc(mysql_query("select count(*)as num from member where m_username='$m_username' and m_email='$m_email'"));
	$resultArray = array();
	if(!$m_username)$err="กรุณากรอก Username";
	else if(!$m_email)$err="กรุณากรอก อีเมลล์";
	else if(!validmail($m_email))$err="อีเมลล์ไม่ถูกต้องตามรูปแบบ";
	else if($row['num']==0)$err="ไม่พบ Username หรือ อีเมลล์นี้ในระบบ";
	else{
		$to = $m_email;
		$subject="แจ้งรหัสผ่านสำหรับใช้งาน $cfg_domain";
		$from="info@$cfg_domain";
		$mailheaders  = "MIME-Version: 1.0\r\n";
		$mailheaders .= "Content-type: text/html; charset=utf-8 \r\n";
		$mailheaders.= "From: $cfg_domain <$from> \n";
		$mailheaders.= "Reply-To: <{$m_email}>\n\n";
		
		$msg	= "Username : $m_username<br>";
		$msg	.= "Email : $m_email<br>";
		$msg	.= "Password : <b>$m_username<b><br>";
		@mail($to,$subject,$msg,$mailheaders);
		$data['result'] = 'OK';
	}
	array_push($resultArray,$data);
	if ($err) $data['result'] = $err;
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	echo json_encode($resultArray);
	//createOutput($format, $data);
}

#format=json&method=memberdetail&m_id=3
function memberdetail()
{
	if(isset($_GET["m_id"])){
		$m_id = $_GET['m_id'];
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST['m_id'];
	}
	$objQuery = mysql_query("select * from member where m_id='$m_id'") or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$numrow = mysql_num_rows($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		
		array_push($resultArray,$arrCol);
	}
	mysql_close($objConnect);
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	echo json_encode($resultArray);
	//createOutput($format, $data);
}

#format=json&method=editmember&m_name=เจ้าหน้าที่&m_tel=12345678&m_email=gtamafia.th@gmail.com&m_id=3
function editmember(){
	if(isset($_GET['m_name'])){
		$m_name = $_GET['m_name'];
	}else if(isset($_POST["m_name"])){
		$m_name = $_POST["m_name"];
	}
	if(isset($_GET['m_tel'])){
		$m_tel = $_GET['m_tel'];
	}else if(isset($_POST["m_tel"])){
		$m_tel = $_POST["m_tel"];
	}
	if(isset($_GET['m_email'])){
		$m_email = $_GET['m_email'];
	}else if(isset($_POST["m_email"])){
		$m_email = $_POST["m_email"];
	}
	if(isset($_GET['m_id'])){
		$m_id = $_GET['m_id'];
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST["m_id"];
	}
	if(isset($_GET['m_password'])){
		$m_password = $_GET['m_password'];
	}else if(isset($_POST["m_password"])){
		$m_password = $_POST["m_password"];
	}
	if(isset($_GET['m_code'])){
		$m_code = $_GET['m_code'];
	}else if(isset($_POST["m_code"])){
		$m_code = $_POST["m_code"];
	}
	
	
	
	
	$sql = "UPDATE member 
	SET m_name = '$m_name',
	m_tel = '$m_tel',
	m_email = '$m_email',
	m_password = '$m_password',
	m_code = '$m_code'
	WHERE m_id = '$m_id'
	";
	$exe = mysql_query($sql);
	$resultArray = array();
	$arrCol = array();
	if($exe){
		$arrCol["result"] = "OK";
	}else{
		$arrCol["result"] = "ERROR";
	}
	array_push($resultArray,$arrCol);
	echo json_encode($resultArray);
}

#format=json&method=t_listcourse&m_id=2
function t_listcourse()
{
	if(isset($_GET['m_id'])){
		$m_id = $_GET['m_id'];
	}else if($_POST['m_id']){
		$m_id = $_POST['m_id'];
	}
	$where = " where m_id=$m_id and course_name like '%$search%'";
	$sql = "select * from course $where order by course_name asc";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$numrow = mysql_num_rows($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		
		array_push($resultArray,$arrCol);
	}
	mysql_close($objConnect);

	echo json_encode($resultArray);
	/*$res = mysql_query($sql) or die(mysql_error());
	while($row = mysql_fetch_assoc($res))
	{
		$course[] = $row;
	}
	$data['result'] = 'OK';
	$data['course'] = $course;
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	createOutput($format, $data);*/
}

#format=json&method=chkaccept&course_id=1&m_id=14
function chkaccept(){
	if(isset($_GET["m_id"])){
		$m_id = $_GET["m_id"];
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST["m_id"];
	}
	if(isset($_GET["course_id"])){
		$course_id = $_GET["course_id"];
	}else if(isset($_POST["course_id"])){
		$course_id = $_POST["course_id"];
	}
	
	$sql="select status_id from course_regis where m_id = $m_id and course_id = $course_id";
 	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
}

#format=json&method=t_listlesson&course_id=2
function t_listlesson()
{
	global $root_path;
	global $file_name;
	if(isset($_GET["course_id"])){
		$course_id = $_GET["course_id"];
	}else if(isset($_POST["course_id"])){
		$course_id = $_POST["course_id"];
	}
	$where="where course_id='$course_id' and lesson_name like '%$search%'";
 	$sql="select * from lesson $where order by lesson_name asc";
 	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
	/*while($row = mysql_fetch_assoc($res))
	{
		$row['url'] = "$root_path/$file_name?method=lessondetail&lesson_id=$row[lesson_id]";
		$lesson[] = $row;
	}
	$data['result'] = 'OK';
	$data['lesson'] = $lesson;*/
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	//createOutput($format, $data);
}

#method=lessondetail&lesson_id=1
function lessondetail()
{
	$lesson=mysql_fetch_assoc(mysql_query("select * from lesson where lesson_id='$_GET[lesson_id]'"));
?>
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<div class="box">
	<h2><?php echo $lesson['lesson_name'];?></h2>
	<?php if($err)echo "<div id=error_msg>$err</div>";?>
	<div class="boxContent">
		<?php
		echo $lesson['lesson_detail'];
		?>
    </div>
</div>
<?php
}

#format=json&method=t_updateexam&lesson_id=3&exam_start=2011-03-28 13:00:00&exam_stop=2011-03-28 20:00:00&exam_open=1
function t_updateexam()
{
	if(isset($_GET["lesson_id"])){
		$lesson_id = $_GET['lesson_id'];
	}else if(isset($_POST["lesson_id"])){
		$lesson_id = $_POST['lesson_id'];
	}
	if(isset($_GET["exam_start"])){
		$exam_start = $_GET['exam_start'];
	}else if(isset($_POST["exam_start"])){
		$exam_start = $_POST['exam_start'];
	}
	if(isset($_GET["exam_stop"])){
		$exam_stop = $_GET['exam_stop'];
	}else if(isset($_POST["exam_stop"])){
		$exam_stop = $_POST['exam_stop'];
	}
	if(isset($_GET["exam_open"])){
		$exam_open = $_GET['exam_open'];
	}else if(isset($_POST["exam_open"])){
		$exam_open = $_POST['exam_open'];
	}
	$sql = "update lesson set exam_start='$exam_start',exam_stop='$exam_stop',exam_open='$exam_open' where lesson_id='$lesson_id'";
	$res = mysql_query($sql);
	$resultArray = array();
	if($res)
	{
		$data['result'] = 'OK';
		$data['affected_rows'] = mysql_affected_rows();
	}
	else
	{
		$data['result'] = 'ERROR';
	}
	//$data["sql"] = $sql;
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	array_push($resultArray,$data);
	echo json_encode($resultArray);
	//createOutput($format, $data);
}
#format=json&method=t_showexamtime&lesson_id=3
function t_showexamtime()
{
	if(isset($_GET["lesson_id"])){
		$lesson_id = $_GET['lesson_id'];
	}else if(isset($_POST["lesson_id"])){
		$lesson_id = $_POST['lesson_id'];
	}
	$sql = "SELECT * FROM lesson WHERE lesson_id='$lesson_id'";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
	//createOutput($format, $data);
}

#format=json&method=t_listdepartment
function t_listdepartment()
{
		$sql="select * from department order by dep_id";
		$res=mysql_query($sql);
		$i=0;
		while($dep=mysql_fetch_assoc($res)){
			$department[$i] = $dep;
			$sql="select * from branch where dep_id='$dep[dep_id]' order by branch_id";
			$res2=mysql_query($sql);
			while($branch=mysql_fetch_assoc($res2)){
				$department[$i]['branch'] = $branch;
			}
			++$i;
		}
	$data['result'] = 'OK';
	$data['department'] = $department;
	if(isset($_GET['format'])){
 $format =  $_GET['format'];
}else if(isset($_POST['format'])){
 $format =  $_POST['format'];
}
	createOutput($format, $data);
}
#format=json&method=listdepartment_regis&course_id=1
function listdepartment_regis(){
	if(isset($_GET["course_id"])){
		$course_id = $_GET["course_id"];
	}else if(isset($_POST['course_id'])){
		$course_id = $_POST['course_id'];
	}
	$sql = "
	SELECT 
		department.dep_name,
		department.dep_id
	FROM department
	INNER JOIN branch ON (department.dep_id = branch.dep_id)
	INNER JOIN member ON (member.branch_id = branch.branch_id)
	INNER JOIN course_regis ON (course_regis.m_id = member.m_id)
	WHERE 
		course_regis.course_id = '$course_id'
	GROUP 
		BY department.dep_id
	";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
	//course_id
}

#format=json&method=listdepartment
function listdepartment(){
	$sql = "SELECT * FROM department";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
}
#format=json&method=listmajor&dep_id=1
function listmajor(){
	if(isset($_GET["dep_id"])){
		$dep_id = $_GET['dep_id'];
	}else if(isset($_POST["dep_id"])){
		$dep_id = $_POST["dep_id"];
	}
	$sql = "SELECT * FROM branch WHERE dep_id = '$dep_id'";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
}

function regiscourse(){
	if(isset($_GET['course_id'])){
		$course_id = $_GET['course_id'];
	}else if(isset($_POST['course_id'])){
		$course_id = $_POST['course_id'];
	}
	if(isset($_GET['m_id'])){
		$m_id = $_GET['m_id'];
	}else if(isset($_POST['m_id'])){
		$m_id = $_POST['m_id'];
	}
	if(isset($_GET['approve'])){
		$approve = $_GET['approve'];
	}else if(isset($_POST['approve'])){
		$approve= $_POST['approve'];
	}
	
	$sql = "UPDATE course_regis SET status_id = $approve WHERE m_id = $m_id AND course_id = $course_id";
	$exe = mysql_query($sql);
	if($approve==1){
		$result = 'อนุมัติเรียบร้อยแล้ว';
	}else{
		$result = "ยกเลิกการอนุมัติ";	
	}
	echo $result;
	
}

function getstudent_status($m_id,$course_id){
	$sql = "SELECT status_id FROM course_regis WHERE m_id = $m_id AND course_id = $course_id";
	$exe = mysql_query($sql);
	$data = mysql_fetch_array($exe);
	$text = "";
	if($data['status_id']==1){
		$text = "อนุมัติเรียบร้อยแล้ว";
	}else{
		$text = "ยังไม่ได้ทำการอนุมัติ";	
	}
	return $text;
}
#format=json&method=t_liststudent&course_id=1&branch_id=1
function t_liststudent()
{
	if(isset($_GET['course_id'])){
		$course_id = $_GET['course_id'];
	}else if(isset($_POST['course_id'])){
		$course_id = $_POST['course_id'];
	}
	if(isset($_GET['branch_id'])){
		$branch_id = $_GET['branch_id'];
	}else if(isset($_POST['branch_id'])){
		$branch_id = $_POST['branch_id'];
	}
	
	//$course_id = $_GET['course_id'];
	//$branch_id = $_GET['branch_id'];
	$sql="select a.m_id,m_username,m_code,m_name,m_pic,group_id,a.status_id,m_tel,m_email from course_regis a,member b where a.m_id=b.m_id and course_id='$course_id' and branch_id='$branch_id' $where order by group_id asc,m_code,m_name";
	//echo $sql;
	
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
			$arrCol["status"] = getstudent_status($obResult['m_id'],$course_id);
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
	/*$res=mysql_query($sql);
	while($row = mysql_fetch_assoc($res))
	{
		$student[] = $row;
	}
	$data['result'] = 'OK';
	$data['student'] = $student;
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	createOutput($format, $data);*/
}

#format=json&method=showscore&m_id=3
function showscore(){
	if(isset($_GET["m_id"])){
		$m_id = $_GET["m_id"];	
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST["m_id"];
	}
	$sql = "
	SELECT
		exam_start,
		ex_score,
		ex_fullscore,
		lesson_name
	FROM examination
	INNER JOIN lesson ON (lesson.lesson_id = examination.lesson_id)
	WHERE examination.m_id = '$m_id'
	";

	
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);
	return $resultArray;
	//echo json_encode($resultArray);
}

#format=json&method=t_viewscore&course_id=1&branch_id=1
function t_viewscore()
{
	$course_id = $_GET['course_id'];
	$branch_id = $_GET['branch_id'];
	$sql="select * from lesson where course_id='$_GET[course_id]' and have_exam=1";
	$res=mysql_query($sql);
	$num=mysql_num_rows($res);
	$total=0;
	while($row = mysql_fetch_assoc($res))
	{
		$total += $lesson['question_num'];
		$lessons[] = $row;
	}
	$median=$total/2;
	$sql="select a.m_id,m_username,m_name,group_id,a.status_id from course_regis a,member b where a.m_id=b.m_id and course_id='$_GET[course_id]' and b.branch_id='$branch_id' order by m_name asc";
	$res=mysql_query($sql);
	$number=mysql_num_rows($res);
		$i=0;
		while($row=mysql_fetch_assoc($res)){
			$members[$i] = $row;
			$status=mysql_fetch_assoc(mysql_query("select * from status where status_id='$row[status_id]'"));
			$groups=mysql_fetch_assoc(mysql_query("select * from groups where group_id='$row[group_id]'"));

			$sql="select * from lesson where course_id='$_GET[course_id]' and have_exam=1";
  			$res2=mysql_query($sql);
			$sum=0;
			while($lesson=mysql_fetch_assoc($res2)){
				$ex=mysql_fetch_assoc(mysql_query("select * from examination where lesson_id='$lesson[lesson_id]' and m_id='$row[m_id]'"));
				$sum+=(int)$ex['ex_score'];
				$members[$i]['score'][] = (int)$ex['ex_score'];
			}
			$members[$i]['sum'] = $sum;
			$score[]=$sum;
			
			++$i;
		}
	$data['result'] = 'OK';
	$data['lesson'] = $lessons;
	$data['member'] = $members;
	$data['min'] = min($score);
	$data['max'] = max($score);
	$data['avg'] = number_format(array_sum($score)/count($score),2);
	//echo "<pre>";print_r($data);
	
	if(isset($_GET['format'])){
 $format =  $_GET['format'];
}else if(isset($_POST['format'])){
 $format =  $_POST['format'];
}
	createOutput($format, $data);
}

#format=json&method=t_listnews&m_id=2
function t_listnews()
{
	global $root_path;
	global $file_name;
	$where=" where m_id='$_GET[m_id]' and news_subject like '%$search%'";
	$sql="select * from news $where order by news_addtime desc";
	$res=mysql_query($sql) or die(mysql_error());
	while($row = mysql_fetch_assoc($res))
	{
		$row['url'] = "$root_path/$file_name?method=newsdetail&news_id=$row[news_id]";
		$news[] = $row;
	}
	$data['result'] = 'OK';
	$data['news'] = $news;
	if(isset($_GET['format'])){
 $format =  $_GET['format'];
}else if(isset($_POST['format'])){
 $format =  $_POST['format'];
}
	createOutput($format, $data);
}

#format=json&method=t_addnews&m_id=2&news_subject=หัวข้อ&news_detail=รายละเอียด
function t_addnews()
{
	if(isset($_GET['news_subject'])){
		$news_subject = $_GET['news_subject'];
	}else if(isset($_POST['news_subject'])){
		$news_subject = $_POST['news_subject'];
	}
	if(isset($_GET['news_detail'])){
		$news_detail=$_GET['news_detail'];
	}else if(isset($_POST['news_detail'])){
		$news_detail=$_POST['news_detail'];
	}
	if(isset($_GET["m_id"])){
		$m_id = $_GET['m_id'];	
	}else if(isset($_POST['m_id'])){
		$m_id = $_POST['m_id'];
	}
	if(!$news_subject)$err="กรุณากรอก หัวเรื่อง";
	else if(!$news_detail)$err="กรุณากรอก รายละเอียด";
	else{
		$sql="insert into news(news_subject, news_detail, news_addtime, m_id) values('$news_subject', '$news_detail', now(), '$m_id')";
		mysql_query($sql);
		$data['result'] = 'OK';
	}
	if($err)$data['result'] = $err;
	
	$resultArray = array();
	
	array_push($resultArray,$data);
	/*if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	createOutput($format, $data);*/
	echo json_encode($resultArray);
	
}

#format=json&method=t_updatenews&m_id=2&news_id=3&news_subject=หัวข้อใหม่&news_detail=รายละเอียดใหม่
function t_updatenews()
{
	
	if(isset($_GET['news_subject'])){
		$news_subject = $_GET['news_subject'];
	}else if(isset($_POST['news_subject'])){
		$news_subject = $_POST['news_subject'];
	}
	if(isset($_GET['news_detail'])){
		$news_detail=$_GET['news_detail'];
	}else if(isset($_POST['news_detail'])){
		$news_detail=$_POST['news_detail'];
	}
	if(isset($_GET["m_id"])){
		$m_id = $_GET['m_id'];	
	}else if(isset($_POST['m_id'])){
		$m_id = $_POST['m_id'];
	}
	if(isset($_GET['news_id'])){
		$news_id = $_GET['news_id'];
	}else if(isset($_POST['news_id'])){
		$news_id = $_POST['news_id'];
	}
	if(!$news_subject)$err="กรุณากรอก หัวเรื่อง";
	else if(!$news_detail)$err="กรุณากรอก รายละเอียด";
	else{
		$sql="update news set news_subject='$news_subject', news_detail='$news_detail', news_edittime=now() where news_id='$news_id' and m_id='$m_id'";
		$res = mysql_query($sql);
		if($res)
		{
			$data['result'] = 'OK';
			$data['affected_rows'] = mysql_affected_rows();
		}
		else
		{
			$data['result'] = 'ERROR';
		}
	}
	if($err)$data['result'] = $err;
	
	$resultArray = array();
	
	array_push($resultArray,$data);
	
	echo json_encode($resultArray);
	/*if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	createOutput($format, $data);*/
}

#format=json&method=t_delnews&news_id=2&m_id=2
function t_delnews()
{
	if(isset($_GET['news_id'])){
		$news_id = $_GET['news_id'];
	}else if(isset($_POST['news_id'])){
		$news_id = $_POST['news_id'];
	}
	if(isset($_GET['m_id'])){
		$m_id = $_GET['m_id'];
	}else if(isset($_POST['m_id'])){
		$m_id = $_POST['m_id'];
	}
	$res = mysql_query("delete from news where news_id='$news_id' and m_id='$m_id'");
	if($res)
	{
		$data['result'] = 'OK';
		$data['affected_rows'] = mysql_affected_rows();
	}
	else
	{
		$data['result'] = 'ERROR';
	}
	
	$resultArray = array();
	
	array_push($resultArray,$data);
	
	echo json_encode($resultArray);
	/*if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	createOutput($format, $data);*/
}

#format=json&method=s_listcourse
function s_listcourse()
{
	$where = " where course_name like '%$search%'";
	$sql = "select * from course $where order by course_name asc";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
	/*while($row = mysql_fetch_assoc($res))
	{
		$course[] = $row;
	}
	$data['result'] = 'OK';
	$data['course'] = $course;*/
	if(isset($_GET['format'])){
		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
		$format =  $_POST['format'];
	}
	//createOutput($format, $data);
}

#format=json&method=s_listregisteredcourse&m_id=3
function s_listregisteredcourse()
{
	if(isset($_GET['m_id'])){
		$m_id = $_GET['m_id'];
	}else if(isset($_POST['m_id'])){
		$m_id = $_POST['m_id'];
	}
	$where = " where course_name like '%$search%'";
	$sql = "select b.* from course_regis a,course b $where and a.course_id=b.course_id and a.m_id='$m_id' order by course_name asc";
	$objQuery = mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	
	while($obResult = mysql_fetch_array($objQuery)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}

	mysql_close($objConnect);

	echo json_encode($resultArray);
	/*while($row = mysql_fetch_assoc($res))
	{
		$course_regis[] = $row;
	}
	$data['result'] = 'OK';
	$data['course_regis'] = $course_regis;*/
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	//createOutput($format, $data);
}

#format=json&method=s_courseregister&m_id=3&course_id=1
function s_courseregister()
{
	if(isset($_GET["course_id"])){
		$course_id = $_GET["course_id"];
	}else if(isset($_POST["course_id"])){
		$course_id = $_POST["course_id"];
	}
	if(isset($_GET["m_id"])){
		$m_id = $_GET["m_id"];
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST["m_id"];
	}
	$num=mysql_num_rows(mysql_query("select regis_id from course_regis where course_id='$course_id' and m_id='$m_id'"));
	$resultArray = array();
	$data = array();
	if($num==0){
		mysql_query("insert into course_regis(regis_time,course_id,m_id) values('".date('Y-m-d H:i:s')."','$course_id','$m_id')");
		$data['result'] = 'OK';
	}
	else
	{
		$data['result'] = 'ลงทะเบียนซ้ำ';
	}
	$data['sql'] = "select regis_id from course_regis where course_id='$course_id' and m_id='$m_id'";
	array_push($resultArray,$data);
	
	echo json_encode($resultArray);
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	//createOutput($format, $data);
}
# เช็คว่าลงทะเบียนซ้ำหรือเปล่า
#format=json&method=chk_courseregister&m_id=3&course_id=1
function chk_courseregister()
{
	if(isset($_GET['course_id'])){
		$course_id = $_GET['course_id'];
	}else if($_POST["course_id"]){
		$course_id = $_POST['course_id'];
	}
	if(isset($_GET['m_id'])){
		$m_id = $_GET['m_id'];
	}else if($_POST['m_id']){
		$m_id = $_POST['m_id'];
	}
	$num=mysql_num_rows(mysql_query("select regis_id from course_regis where course_id='$course_id' and m_id='$m_id'"));
	$data = array();
	$resultArray = array();
	if($num>0){
		//mysql_query("insert into course_regis(regis_time,course_id,m_id) values('".date('Y-m-d H:i:s')."','$course_id','$m_id')");
		$data['result'] = 'regised';
	}
	else
	{
		$data['result'] = 'noregis';
	}
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	array_push($resultArray,$data);
	echo json_encode($resultArray);
	//createOutput($format, $data);
}

#format=json&method=listallnews
function listallnews()
{
	global $root_path;
	global $file_name;
	$sql="select * from news ,member where news.m_id=member.m_id order by news_addtime desc";
	$res=mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($res);
	$resultArray = array();
	while($obResult = mysql_fetch_array($res)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($res,$i)] = $obResult[$i];
			$obResult['url'] = "$root_path/$file_name?method=newsdetail&news_id=$obResult[news_id]";
			$arrCol['url'] = $obResult['url'];
		}
		array_push($resultArray,$arrCol);
	
	}
	echo json_encode($resultArray);
	/*while($row = mysql_fetch_assoc($res))
	{
		$row['url'] = "$root_path/$file_name?method=newsdetail&news_id=$row[news_id]";
		$news[] = $row;
	}
	$data['result'] = 'OK';
	$data['news'] = $news;*/
	if(isset($_GET['format'])){
		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
		$format =  $_POST['format'];
	}
	//createOutput($format, $data);
}

#method=newsdetail&news_id=3
function newsdetail()
{
	$row=mysql_fetch_assoc(mysql_query("select * from news,member where news_id='$_GET[news_id]' and news.m_id=member.m_id"));
	echo "
	<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> 
	<div class='box'>
		<h2> ".$row['news_subject']."</h2>
		<div class='boxContent'>
			".$row['news_detail']."
			<hr />
			<strong>เพิ่มเมื่อ :</strong>". $row['news_addtime']."<br />
			<strong>โดย :</strong> อ.".$row['m_name']."
		</div>
	</div>";
}

function php_getquestion()
{
	global $root_path;
	if(isset($_GET["lesson_id"])){
		$lesson_id = $_GET["lesson_id"];
	}else if(isset($_POST["lesson_id"])){
		$lesson_id = $_POST["lesson_id"];
	}
	if(isset($_GET["m_id"])){
		$m_id = $_GET["m_id"];
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST["m_id"];
	}
	$lesson=mysql_fetch_assoc(mysql_query("select * from lesson where lesson_id='$lesson_id'"));
	$ex=mysql_fetch_assoc(mysql_query("select count(*) as num from examination where lesson_id='$lesson_id' and m_id='$m_id'"));
	$res=mysql_query("select * from course_regis where course_id='$lesson[course_id]' and m_id='$m_id' and status_id=1");
	
	if($lesson['exam_open']==0) $err = 'แบบทดสอบนี้ยังไม่เปิดให้ใช้งาน';
	else if($ex['num']>0)$err = 'เคยทำข้อสอบนี้ไปแล้ว';
	else if(mysql_num_rows($res)==0) $err = 'ไม่ได้ลงทะเบียนเรียนในวิชานี้ หรือยังไม่ได้อนุมัติการลงทะเบียน';
	else if(strtotime($lesson['exam_start'])>time()) $err = "ยังไม่ถึงเวลาทำแบบทดสอบ ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else if(strtotime($lesson['exam_stop'])<time()) $err= "หมดเวลาทำแบบทดสอบแล้ว ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else
	{
		$choises='';
		if($lesson['exam_type']==0){
			$res1=mysql_query("select * from question where lesson_id='$lesson_id' order by rand() limit $lesson[question_num]");
			$i=0;
			while($rs=mysql_fetch_assoc($res1)){
				if($rs['question_pic'] != '') $rs['pic_url'] = "$root_path/questionpic/$rs[question_pic]";
				else $rs['pic_url'] = '';
				$questions[]=$rs;
			}
		}else{
			$res_qs=mysql_query("select * from question_special where lesson_id='$lesson_id'");
			while($qs=mysql_fetch_assoc($res_qs)){
				$resl=mysql_query("select * from question where lesson_id='$qs[master_lesson_id]' order by rand() limit $qs[qs_amount]");
				while($rs=mysql_fetch_assoc($resl)){
					$questions[]=$rs;
				}
			}
		}
		foreach($questions as $key => $question){
			++$i;
			unset($choises);
			$correct=mysql_fetch_assoc(mysql_query("select * from choise where question_id='$question[question_id]' and choise_correct = '1'"));
			$choises[]=$correct;
			$res2=mysql_query("select * from choise where question_id='$question[question_id]' and choise_id!='$correct[choise_id]' order by rand() limit 4");
			while($choise=mysql_fetch_assoc($res2)){
				$choises[]=$choise;
			}
			shuffle($choises);
			$questions[$key]['choise'] = $choises;
		}
	}
	if ($err)
	{
		$data['result'] = $err;
	}
	else
	{
		$data['result'] = 'OK';
		$data['question'] = $questions;
	}
	
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	//echo "<pre>";print_r($data);
	//createOutput($format, $data);
	return $data;
}


#format=json&method=s_getquestion&lesson_id=2&m_id=3
function s_getquestion()
{
	global $root_path;
	if(isset($_GET["lesson_id"])){
		$lesson_id = $_GET["lesson_id"];
	}else if(isset($_POST["lesson_id"])){
		$lesson_id = $_POST["lesson_id"];
	}
	if(isset($_GET["m_id"])){
		$m_id = $_GET["m_id"];
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST["m_id"];
	}
	$lesson=mysql_fetch_assoc(mysql_query("select * from lesson where lesson_id='$lesson_id'"));
	$ex=mysql_fetch_assoc(mysql_query("select count(*) as num from examination where lesson_id='$lesson_id' and m_id='$m_id'"));
	$res=mysql_query("select * from course_regis where course_id='$lesson[course_id]' and m_id='$m_id' and status_id=1");
	
	if($lesson['exam_open']==0) $err = 'แบบทดสอบนี้ยังไม่เปิดให้ใช้งาน';
	else if($ex['num']>0)$err = 'เคยทำข้อสอบนี้ไปแล้ว';
	else if(mysql_num_rows($res)==0) $err = 'ไม่ได้ลงทะเบียนเรียนในวิชานี้ หรือยังไม่ได้อนุมัติการลงทะเบียน';
	else if(strtotime($lesson['exam_start'])>time()) $err = "ยังไม่ถึงเวลาทำแบบทดสอบ ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else if(strtotime($lesson['exam_stop'])<time()) $err= "หมดเวลาทำแบบทดสอบแล้ว ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else
	{
		$choises='';
		if($lesson['exam_type']==0){
			$res1=mysql_query("select * from question where lesson_id='$lesson_id' order by rand() limit $lesson[question_num]");
			$i=0;
			while($rs=mysql_fetch_assoc($res1)){
				if($rs['question_pic'] != '') $rs['pic_url'] = "$root_path/questionpic/$rs[question_pic]";
				else $rs['pic_url'] = '';
				$questions[]=$rs;
			}
		}else{
			$res_qs=mysql_query("select * from question_special where lesson_id='$lesson_id'");
			while($qs=mysql_fetch_assoc($res_qs)){
				$resl=mysql_query("select * from question where lesson_id='$qs[master_lesson_id]' order by rand() limit $qs[qs_amount]");
				while($rs=mysql_fetch_assoc($resl)){
					$questions[]=$rs;
				}
			}
		}
		foreach($questions as $key => $question){
			++$i;
			unset($choises);
			$correct=mysql_fetch_assoc(mysql_query("select * from choise where question_id='$question[question_id]' and choise_correct = '1'"));
			$choises[]=$correct;
			$res2=mysql_query("select * from choise where question_id='$question[question_id]' and choise_id!='$correct[choise_id]' order by rand() limit 4");
			while($choise=mysql_fetch_assoc($res2)){
				$choises[]=$choise;
			}
			shuffle($choises);
			$questions[$key]['choise'] = $choises;
		}
	}
	if ($err)
	{
		$data['result'] = $err;
	}
	else
	{
		$data['result'] = 'OK';
		$data['question'] = $questions;
	}
	
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	//echo "<pre>";print_r($data);
	createOutput($format, $data);
}
#format=json&method=show_schedule&course_id=1
function show_schedule(){
	if(isset($_GET['course_id'])){
		$course_id = $_GET['course_id'];
	}else if(isset($_POST['course_id'])){
		$course_id = $_POST['course_id'];
	}
	
	if($course_id != ''){
		$cond = "lesson.course_id = '$course_id'";	
	}else{
		$cond = "1 = 1";	
	}
	$sql="
	SELECT
		course_name,
		lesson_id,
		lesson_name,
		exam_start
	FROM lesson
	INNER JOIN course ON (lesson.course_id = course.course_id)	
	WHERE 
	$cond
	AND exam_open = 1
	ORDER BY exam_start DESC
	";
	$res=mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($res);
	$resultArray = array();
	while($obResult = mysql_fetch_array($res)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($res,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	
	}
	echo json_encode($resultArray);
}

function php_savescore()
{
	if(isset($_GET["lesson_id"])){
		$lesson_id = $_GET["lesson_id"];
	}else if(isset($_POST["lesson_id"])){
		$lesson_id = $_POST["lesson_id"];
	}
	if(isset($_GET["m_id"])){
		$m_id = $_GET["m_id"];
	}else if(isset($_POST["m_id"])){
		$m_id = $_POST["m_id"];
	}
	if(isset($_GET["ex_score"])){
		$ex_score = $_GET["ex_score"];
	}else if(isset($_POST["ex_score"])){
		$ex_score = $_POST["ex_score"];
	}
	$lesson=mysql_fetch_assoc(mysql_query("select * from lesson where lesson_id='$lesson_id'"));
	$ex=mysql_fetch_assoc(mysql_query("select count(*) as num from examination where lesson_id='$lesson_id' and m_id='$m_id'"));
	$res=mysql_query("select * from course_regis where course_id='$lesson[course_id]' and m_id='$m_id' and status_id=1");
	
	if($lesson['exam_open']==0) $err = 'แบบทดสอบนี้ยังไม่เปิดให้ใช้งาน';
	else if($ex['num']>0)$err = 'เคยทำข้อสอบนี้ไปแล้ว';
	else if(mysql_num_rows($res)==0) $err = 'ไม่ได้ลงทะเบียนเรียนในวิชานี้ หรือยังไม่ได้อนุมัติการลงทะเบียน';
	else if(strtotime($lesson['exam_start'])>time()) $err = "ยังไม่ถึงเวลาทำแบบทดสอบ ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else if(strtotime($lesson['exam_stop'])<time()) $err= "หมดเวลาทำแบบทดสอบแล้ว ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else
	{
		$ex_time=date('Y-m-d H:i:s');
		$ex_fullscore=$lesson['question_num'];
		$sql="insert into examination(ex_time,ex_score,ex_fullscore,lesson_id,m_id,ex_from) values('$ex_time','$ex_score','$ex_fullscore','$lesson_id','$m_id','1')";
		mysql_query($sql)or die(mysql_error());
	}
	if ($err)
	{
		$data['result'] = $err;
	}
	else
	{
		$data['result'] = 'บันทึกคะแนนเรียบร้อยแล้ว';
	}
	
	if(isset($_GET['format'])){
 $format =  $_GET['format'];
}else if(isset($_POST['format'])){
 $format =  $_POST['format'];
}
	//createOutput($format, $data);
	echo $data['result'];
}



#format=json&method=s_savescore&lesson_id=2&m_id=3&ex_score=9
function s_savescore()
{
	$lesson=mysql_fetch_assoc(mysql_query("select * from lesson where lesson_id='$_GET[lesson_id]'"));
	$ex=mysql_fetch_assoc(mysql_query("select count(*) as num from examination where lesson_id='$_GET[lesson_id]' and m_id='$_GET[m_id]'"));
	$res=mysql_query("select * from course_regis where course_id='$lesson[course_id]' and m_id='$_GET[m_id]' and status_id=1");
	
	if($lesson['exam_open']==0) $err = 'แบบทดสอบนี้ยังไม่เปิดให้ใช้งาน';
	else if($ex['num']>0)$err = 'เคยทำข้อสอบนี้ไปแล้ว';
	else if(mysql_num_rows($res)==0) $err = 'ไม่ได้ลงทะเบียนเรียนในวิชานี้ หรือยังไม่ได้อนุมัติการลงทะเบียน';
	else if(strtotime($lesson['exam_start'])>time()) $err = "ยังไม่ถึงเวลาทำแบบทดสอบ ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else if(strtotime($lesson['exam_stop'])<time()) $err= "หมดเวลาทำแบบทดสอบแล้ว ($lesson[exam_start] ถึง $lesson[exam_stop])";
	else
	{
		$ex_time=date('Y-m-d H:i:s');
		$ex_fullscore=$lesson['question_num'];
		$sql="insert into examination(ex_time,ex_score,ex_fullscore,lesson_id,m_id) values('$ex_time','$_GET[ex_score]','$ex_fullscore','$_GET[lesson_id]','$_GET[m_id]')";
		mysql_query($sql)or die(mysql_error());
	}
	if ($err)
	{
		$data['result'] = $err;
	}
	else
	{
		$data['result'] = 'OK';
	}
	
	if(isset($_GET['format'])){
 $format =  $_GET['format'];
}else if(isset($_POST['format'])){
 $format =  $_POST['format'];
}
	createOutput($format, $data);
}

#format=json&method=s_getscore&lesson_id=2&m_id=3
function s_getscore()
{
	if(isset($_GET["lesson_id"])){
		$lesson_id = $_GET["lesson_id"];
	}else if($_POST["lesson_id"]){
		$lesson_id = $_POST["lesson_id"];
	}
	if(isset($_GET["m_id"])){
		$m_id = $_GET["m_id"];
	}else if($_POST["m_id"]){
		$m_id = $_POST["m_id"];
	}
	$res = mysql_query("select * from examination where lesson_id='$lesson_id' and m_id='$m_id'");
	$resultArray = array();
	if(mysql_num_rows($res) == 0)
	{
		$data['result'] = $err;
	}
	else
	{
		$data['result'] = 'OK';
		$row = mysql_fetch_assoc($res);
		$data['ex_score'] = $row['ex_score'];
		$data['ex_fullscore'] = $row['ex_fullscore'];
	}
	array_push($resultArray,$data);
	if(isset($_GET['format'])){
 		$format =  $_GET['format'];
	}else if(isset($_POST['format'])){
 		$format =  $_POST['format'];
	}
	createOutput($format, $resultArray);
}

function showcourse(){
	if(isset($_POST["course_id"])){
		$course_id = $_POST["course_id"];
	}else if(isset($_GET["course_id"])){
		$course_id = $_GET["course_id"];
	}
	$sql = "
	SELECT 
		course_name,
		m_name
	FROM 
		course
	INNER JOIN member ON (course.m_id = member.m_id)
	WHERE course_id = '$course_id'
	";
	$res=mysql_query($sql) or die(mysql_error());
	$intNumField = mysql_num_fields($res);
	$resultArray = array();
	while($obResult = mysql_fetch_array($res)){
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++){
			$arrCol[mysql_field_name($res,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	
	}
	echo json_encode($resultArray);
	
}
function createOutput($format, $posts)
{
/* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json');
    echo json_encode($posts);
  }
  else {
    header('Content-type: text/xml');
    echo array_to_xml($posts, new SimpleXMLElement("<?xml version=\"1.0\"?><root/>"))->asXML();
  }
}

function array_to_xml(array $arr, SimpleXMLElement $xml)
{
    foreach ($arr as $k => $v) {
        is_array($v)
            ? array_to_xml($v, $xml->addChild($k))
            : $xml->addChild($k, $v);
    }
    return $xml;
}

/*
function json_encode( $data ) 
{
    return  __json_encode( $data );
}
*/
function __json_encode( $data ) {            
    if( is_array($data) || is_object($data) ) { 
        $islist = is_array($data) && ( empty($data) || array_keys($data) === range(0,count($data)-1) ); 
        
        if( $islist ) { 
            $json = '[' . implode(',', array_map('__json_encode', $data) ) . ']'; 
        } else { 
            $items = Array(); 
            foreach( $data as $key => $value ) { 
                $items[] = __json_encode("$key") . ':' . __json_encode($value); 
            } 
            $json = '{' . implode(',', $items) . '}'; 
        } 
    } elseif( is_string($data) ) { 
        # Escape non-printable or Non-ASCII characters. 
        # I also put the \\ character first, as suggested in comments on the 'addclashes' page. 
        $string = '"' . addcslashes($data, "\\\"\n\r\t/" . chr(8) . chr(12)) . '"'; 
        $json    = ''; 
        $len    = strlen($string); 
        # Convert UTF-8 to Hexadecimal Codepoints. 
        for( $i = 0; $i < $len; $i++ ) { 
            
            $char = $string[$i]; 
            $c1 = ord($char); 
            
            # Single byte; 
            if( $c1 <128 ) { 
                $json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1); 
                continue; 
            } 
            
            # Double byte 
            $c2 = ord($string[++$i]); 
            if ( ($c1 & 32) === 0 ) { 
                $json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128); 
                continue; 
            } 
            
            # Triple 
            $c3 = ord($string[++$i]); 
            if( ($c1 & 16) === 0 ) { 
                $json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 - 128)); 
                continue; 
            } 
                
            # Quadruple 
            $c4 = ord($string[++$i]); 
            if( ($c1 & 8 ) === 0 ) { 
                $u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1; 
            
                $w1 = (54<<10) + ($u<<6) + (($c2 & 15) << 2) + (($c3>>4) & 3); 
                $w2 = (55<<10) + (($c3 & 15)<<6) + ($c4-128); 
                $json .= sprintf("\\u%04x\\u%04x", $w1, $w2); 
            } 
        } 
    } else { 
        # int, floats, bools, null 
        $json = strtolower(var_export( $data, true )); 
    } 
    return $json; 
} 
?>